package com.lt.controller;

import com.lt.entity.Login;
import com.lt.mapper.LoginMapper;
import com.lt.service.LoginService;
import com.lt.utils.JwtUtils;
import com.lt.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @Author :liteng
 * @Time : 2023-10-21 17:30
 * 111
 */


@Slf4j
@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {
    //大会上空间

    //    private LoginMapper loginMapper;
    private final LoginService loginService;

    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @PostMapping
    public Result login(@RequestBody Login user) {
        log.info(String.valueOf(user));
//        log.error(String.valueOf(user));
        int loginAuth = loginService.loginAuth(user.getNum(), user.getPassword(), user.getIdentity());
        if (loginAuth == -1) {
            return Result.error("用户不存在");
        }
        if (loginAuth == 0) {
            return Result.error("密码错误");
        }
        //生成令牌
        HashMap<String, Object> login = new HashMap<>();
        Long userNum = user.getNum();
        int identity = user.getIdentity();
        login.put("num", userNum);
        login.put("identity", identity);
        String jwt = JwtUtils.generateJwt(login);

        //拿到用户名
        String userName = loginService.getUserName(userNum, identity);
        //返回jwt令牌给前端
        HashMap<Object, Object> map = new HashMap<>();
        map.put("name", userName);
        map.put("identity",String.valueOf(identity));
        map.put("jwt",jwt);

        return Result.success(map);

    }

    /**
     * 修改密码
     *
     * @param num
     * @param originPassword
     * @param newPassword
     * @return
     */
    @GetMapping
    public Result changePasswd(Long num, String originPassword, String newPassword) {
        if (loginService.loginAuth(num, originPassword)) {
            loginService.changePassword(num, newPassword);
            return Result.success("密码修改成功");
        }
        return Result.error("密码修改失败");
    }


}
